package chat.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import chat.server.user.UserManagementMap;

public class ChatOld implements Runnable {
	private Socket socket = null;
	private BufferedReader in = null;
	private PrintWriter out = null;
	private boolean close = false;
	
	public ChatOld(Socket socket) {
		this.socket = socket;
		try {
			out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}

	@Override
	public void run() {
		String u;
		String p;
		String to;
		try {
			u = in.readLine();
			p = in.readLine();			
			String str = null;
			if(UserManagementMap.check(u, p)){
				UserManagementMap.addUser(u, socket);
				while(UserManagementMap.size() <= 1){}
				out.write("To which user you would like to chat " );
				out.write("\n");
				out.write(UserManagementMap.getUserList().toString());
				to = in.readLine();
				PrintWriter toWriter = new PrintWriter(UserManagementMap.getSocket(to).getOutputStream());
				while((str = in.readLine()) != null){
					toWriter.write(str);
					if(str.equals("bye")){
						System.out.println("Logging out.");
						break;
					}
				}
			}	else	{
				System.out.println("Logging out. Invalid Password");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
